package org.streets.workflow.model.io;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;


/**
 * Date utilities.
 * @author Anthony Eden
 *
 */
public class DateUtilities{

    private static final DateUtilities dateUtilities = new DateUtilities();
    private List<SimpleDateFormat> formats;

    /**
     * Construct a new DateUtilities class.
     */
    private DateUtilities(){
        resetFormats();
    }

    /** 
     * Reset the supported formats to the default set. 
     */
    public void resetFormats(){
        formats = new ArrayList<SimpleDateFormat>();

        // ISO formats
        formats.add(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"));
        formats.add(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ"));
        formats.add(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssz"));

        // XPDL examples format
        formats.add(new SimpleDateFormat("MM/dd/yyyy HH:mm:ss a"));

        // alternative formats
        formats.add(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
    }

    /** 
     * Get an instance of the DateUtilities class.
     * @return A DateUtilities instance
     */
    public static DateUtilities getInstance(){
        return dateUtilities;
    }

    /** 
     * Parse the specified date String.
     * @param dateString The date String
     * @return The Date object
     * @throws ParseException If the date format is not supported
     */
    public Date parse(String dateString) throws ParseException{
        Iterator<SimpleDateFormat> iter = formats.iterator();
        while(iter.hasNext()){
            try{
                return ((DateFormat)iter.next()).parse(dateString);
            } catch(ParseException e){
                // do nothing
            }
        }
        throw new ParseException("Unsupported date format", -1);
    }

    /** 
     * Return a List of date formats to try.
     * @return A List of DateFormat objects
     */
    public List<SimpleDateFormat> getFormats(){
        return formats;
    }

}
